#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@NAME          : genttfhtml.py
@TIME          : 2024/11/12 18:55:16
@AUTHOR        : chenlip
@VERSION       : 0.0.1
@DESCRIPTION   : 用于生成ttf字体列表的html文件
'''
# --------------------------引用--------------------------
import os
import jinja2
from .minioact import minioclient
from fontTools.ttLib import TTFont
from PIL import Image, ImageDraw, ImageFont

from app.conf.config import Config as gconf

from .utils import Utils as ut
# --------------------------引用--------------------------

# 生成字体的预览文件
def generate_font_preview(font_path:str, text:str, output_image_path:str):
    '''
        生成字体的预览文件
        :Args:
            - font_path: 字体文件路径
            - text: 预览文本
            - output_image_path: 输出图像路径
    '''
    _fonttyle = ut.getfiletype(font_path)
    # 打开字体文件
    font = TTFont(font_path)
    
    # 获取字体名称
    font_name = font['name'].getName(1, 3, 1, 1033).toStr()
    
    # 创建一个空白图像
    image = Image.new('RGB', (280, 60), (255, 255, 255))
    draw = ImageDraw.Draw(image)
    
    # 加载字体
    if _fonttyle == "truetype":
        pil_font = ImageFont.truetype(font_path, 20)
    elif _fonttyle == "opentype":
        pil_font = ImageFont.FreeTypeFont(font_path, 20)
    else:
        pil_font = ImageFont.FreeTypeFont(font_path, 20)
    
    # 绘制文本
    draw.text((10, 10), text, font=pil_font, fill=(0, 0, 0))
    
    # 绘制字体名称
    draw.text((10, 150), f"Font: {font_name}", font=pil_font, fill=(0, 0, 0))
    
    # 保存图像
    image.save(output_image_path)

# 使用minio的字体文件生成预览图像
def generate_font_preview_minio(obj_path:str):
    '''
        使用minio的字体文件生成预览图像
        :Args:
            - obj_path: 字体文件的minio路径，例如：fonts/chinafont/微软黑体.ttf

        :Return:
            - 预览图像的minio路径, 例如：fonts/chinafont/preview/微软黑体.png
    '''
    _fn = obj_path.split("/")[-1]
    _picname = _fn.split(".")[0] + ".png"
    _txt = "世界这么大，我想去看看！\n 12345...Let's go!"
    _miniopicpath = "no preview"
    print(__file__, "generate_font_preview_minio import minioact success!")
    mc = minioclient()
    
    # 下载字体文件
    _local_path = os.path.join(gconf.TEMPDIR, "fonts")
    if not os.path.exists(_local_path): os.makedirs(_local_path)
    _preview_path = os.path.join(gconf.TEMPDIR, "preview")
    if not os.path.exists(_preview_path): os.makedirs(_preview_path)

    _local_path = os.path.join(_local_path, _fn)
    _preview_path = os.path.join(_preview_path, _picname)

    # minio预览图像
    _miniopicpath = obj_path.replace(_fn,"") + "preview/" + os.path.basename(_preview_path)

    if not mc.isExistObj(_miniopicpath):

        mc.download_file(obj_path, _local_path)
        # 生成预览图像
        try:
            generate_font_preview(_local_path, _txt, _preview_path)
            mc.upload_file(_preview_path, obj_path.replace(_fn,"") + "preview/")
            print(ut.cco(f"生成预览图像成功，地址：{_miniopicpath}", "green"))
        except Exception as err:
            print(ut.cco(f"生成预览图像失败，原因：{err}"))
            _preview_path = "error"
    else:
        print(ut.cco(f"-- 字体预览文件已经存在：{_miniopicpath}", "green"))

    return _miniopicpath

def getFontList(srcdir:str=None, mc=None) -> list:
    '''
        获取字体文件目录下面所有的字体文件字典
        :Args:
            - srcdir: minio中的源文件夹,必须是/结尾, 例如：fonts/chinafont/
        :Return:
            - 字体文件列表, 例如：
            [
                {
                    "refname": "custfont01",
                    "srcfile": "微软黑体.ttf",
                    "encodename": "微软黑体.ttf",
                    "type": "opentype",
                    "size": 2800,
                    "ctime": "2019-10-09",
                },
                {
                    "refname": "custfont02",
                    "srcfile": "微软黑体.ttf",
                    "encodename": "微软黑体.ttf",
                    "type": "truetype",
                    "size": 2800,
                    "ctime": "2019-10-09",
                }
            ]
    '''
    _fontlist = []
    if mc is None:
        print(__file__, "getFontList import minioact success!")
        mc = minioclient()
        
    _mcfilelist = mc.list_obj(srcdir)
    i=1000
    for _f in _mcfilelist:
        i += 1
        _meta = mc.getObjMeta(_f)
        _meta["refname"] = "custfont" + str(i)
        _fontlist.append(_meta)
    
    return _fontlist

# getFontDict

def genTTFHtml(fontlist:list, miniodir:str) -> str:
    '''
        生成字体文件列表的html文件
        :Args:
            - fontlist: 字体文件字典, 例如：
            [
                {
                    "refname": "custfont01",
                    "srcfile": "微软黑体.ttf",
                    "encodename": "微软黑体.ttf",
                    "type": "opentype",
                    "size": 2800,
                    "ctime": "2019-10-09",
                },
                {
                    "refname": "custfont02",
                    "srcfile": "微软黑体.ttf",
                    "encodename": "微软黑体.ttf",
                    "type": "truetype",
                    "size": 2800,
                    "ctime": "2019-10-09",
                }
            ]
            - miniodir: minio中的源文件夹,必须是/结尾, 例如：fonts/chinafont/
        :Return:
            - html文件的minio地址
    '''
    # minio中的源文件夹
    _fontdir = miniodir.split("/")[-2]
    # 1- 生成html文件
    # 指定模板文件../template/fonttemp.html
    _template_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates", "fonttemp.html")
    # 指定生成的html文件(fontlist.html)路径
    _html_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static/temps", f"fontlist-{_fontdir}.html")
    
    # 使用jinjia2模板生成html文件
    with open(_template_file, "r", encoding="utf-8") as f:
        _template = f.read()
        # 生成html文件
        _html = jinja2.Template(_template).render(fontlist=fontlist, fontdir=_fontdir)
        with open(_html_file, "w", encoding="utf-8") as f:
            f.write(_html)
        print(ut.cco("生成html文件成功！", "green"))

    return _html_file

# genTTFHtml

def mainviewfont(miniodir:str):
    # 1- 获取字体文件字典
    _fontlst = getFontList(miniodir)
    # 2- 生成字体文件列表的html文件
    _htmlfile = genTTFHtml(_fontlst, miniodir)
    # _mcfile = ""
    # 3- 上传html文件到minio
    # htmldir = "html/res/viewfonts/"
    # _mcfile = mc.upload_file(_htmlfile, htmldir)
    # print("字体文件列表的html文件地址：\n", mc.mc_bk_url + _mcfile)

    # print(f"-- {miniodir} 目录的字体文件列表的html文件生成已经完成：\n")

